package at.ltasat.classifier.io;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import at.ltasat.classifier.ClazzManager;
import static at.ltasat.util.IO.*;

public abstract class ClazzManagerIO<D> {

	public void write(final OutputStream out, final ClazzManager<D> classes) throws IOException {
		writeInteger(out, classes.size());
		for (int i = 0; i < classes.size(); i++) {
			writeByteArray(out, toRaw(classes.get(i).getData()));
		}
	}

	public ClazzManager<D> read(final InputStream in) throws IOException {
		final D[] ds = createArray(readInteger(in));
		for (int i = 0; i < ds.length; i++) {
			ds[i] = toObject(readByteArray(in));
		}
		return new ClazzManager<D>(ds);
	}

	public abstract D[] createArray(int length);

	public abstract byte[] toRaw(D object);

	public abstract D toObject(byte[] raw);
}
